using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace Elvex
{
    public class UIAsset : MonoBehaviour
    {
        public static void Configure(object id, string asset)
        {
            Elvex.Instance.UIConfiguration.AssetsConfigurations.Add(id, new UIAssetConfigure { ID = id, AssetPath = asset });
        }

        public static void Configure(object id, string asset, Type component)
        {
            Elvex.Instance.UIConfiguration.AssetsConfigurations.Add(id, new UIAssetConfigure { ID = id, AssetPath = asset, Components = new Type[] { component } });
        }

        public static void Configure(object id, string asset, Type[] component)
        {
            Elvex.Instance.UIConfiguration.AssetsConfigurations.Add(id, new UIAssetConfigure { ID = id, AssetPath = asset, Components = component });
        }

        public static UIAsset Load(object id, Transform parent)
        {
            if (!Elvex.Instance.UIConfiguration.AssetsConfigurations.TryGetValue(id, out var cfg))
            {
                Debug.LogErrorFormat("UIConfigure(ID:{0}) is null.", id);
                return null;
            }

            UnityEngine.Object obj = Assets.Load(cfg.AssetPath);
            if (null == obj)
            {
                Debug.LogErrorFormat("Asset({0}) is not found.", cfg.AssetPath);
                return null;
            }

            var go = Instantiate(obj, parent) as GameObject;
            if (null == go)
            {
                Debug.LogErrorFormat("GameObject({0}) Instantiate Failed.", obj);
                return null;
            }

            if (null != cfg.Components)
            {
                foreach (var item in cfg.Components)
                {
                    var component = go.GetComponent(item);
                    if (null == component) go.AddComponent(item);
                }
            }

            var asset = go.GetComponent<UIAsset>();
            if (null == asset) asset = go.AddComponent<UIAsset>();
            asset.ID = id;
            return asset;
        }

        public static T Load<T>(object id, Transform parent) where T : Component
        {
            var asset = Load(id, parent);
            if( null == asset )
            {
                return null;
            }

            var com = asset.GetComponent<T>();
            if (null == com) com = asset.AddComponent<T>();
            return com;
        }

        public object ID { get; private set; }

        public T AddComponent<T>() where T : Component
        {
            return gameObject.AddComponent<T>();
        }

        public void SetActive(bool isactive)
        {
            gameObject.SetActive(isactive);
        }
    }
}